package com.qilu.pe.ui.activity;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.androidkun.xtablayout.XTabLayout;
import com.makeramen.roundedimageview.RoundedImageView;
import com.qilu.pe.R;
import com.qilu.pe.base.Base2Activity;
import com.qilu.pe.base.BaseResult2;
import com.qilu.pe.base.Config;
import com.qilu.pe.base.Global;
import com.qilu.pe.dao.bean.ItemSetDetail;
import com.qilu.pe.dao.bean.SetDetail;
import com.qilu.pe.dao.http.APIRetrofit;
import com.qilu.pe.support.util.GlideUtil;
import com.qilu.pe.ui.fragment.ItemDetail3Fragment;
import com.qilu.pe.ui.fragment.ItemSetDetail1Fragment;
import com.qilu.pe.ui.fragment.ItemSetDetail2Fragment;
import com.qilu.pe.ui.fragment.SetDetail1Fragment;
import com.qilu.pe.ui.fragment.SetDetail2Fragment;
import com.qilu.pe.ui.fragment.SetDetail3Fragment;
import com.ruitu.arad.api.RxUtil;
import com.ruitu.arad.support.view.MeasuredViewPager;
import com.ruitu.arad.util.ToastUtils;

import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

// 项目/套餐详情 1 项目 2 套餐
public class ItemSetDetailActivity extends Base2Activity {
    private TextView tv_name, tv_price, tv_order;
    private ImageView iv_collct;
    RoundedImageView iv_img;
    private XTabLayout tab_2;
    private MeasuredViewPager vp_tab;

    private VpTabAdapter vpTabAdapter;// tab
    private String[] HOME_MODELS;

    private String type = "1";// 1 项目 2 套餐
    private String id;// 项目套餐id

    private ItemSetDetail detail;// 请求得到的项目详情
    private SetDetail setDetail;// 请求得到的套餐详情

    private boolean isCollect = false;// 记录收藏状态

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_item_set_detail;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        tab_2 = findViewById(R.id.tab_2);
        vp_tab = findViewById(R.id.vp_tab);
        tv_name = findViewById(R.id.tv_name);
        tv_price = findViewById(R.id.tv_price);
        tv_order = findViewById(R.id.tv_order);
        iv_collct = findViewById(R.id.iv_collct);
        iv_img = findViewById(R.id.iv_img);

        Bundle bundle = getIntent().getExtras();
        if (null != bundle) {
            id = bundle.getString("id");
            type = bundle.getString("type");
        }

        if (TextUtils.equals("1", type)) {
            setHeadTitle("检测项目");
            HOME_MODELS = new String[]{"项目介绍", "检测样本", "相关疾病"};
        } else {
            setHeadTitle("套餐详情");
            HOME_MODELS = new String[]{"套餐介绍", "检测项目", "检测样本"};
        }

        for (int i = 0; i < 2; i++) {
            tab_2.addTab(tab_2.newTab().setText(HOME_MODELS[i]), i);
        }
        vpTabAdapter = new VpTabAdapter(getSupportFragmentManager());
        vp_tab.setOffscreenPageLimit(9);

        hideProgress();
        if (TextUtils.equals("1", type)) {// 项目
            reqItemSetDetail();
            reqItemCollect("1");// 检测项目是否已收藏
        } else {// 套餐
            reqSetDetail();
            reqSetCollect("1");// 检测套餐是否已收藏
        }
        showProgress();

        setListeners();
    }

    private void setListeners() {
        setOnClickListener(tv_order, iv_collct);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (v == tv_order) {
            startActivity(PlaceOrderActivity.class);
        }
        if (v == iv_collct) {
            if (TextUtils.equals("1", type)) {// 项目
                hideProgress();
                reqItemCollect("");
                showProgress();
            } else {// 套餐
                hideProgress();
                reqSetCollect("");
                showProgress();
            }
        }
    }

    // 设置收藏图标
    private void setCollectIcon() {
        if (isCollect) {
            iv_collct.setImageResource(R.mipmap.item_set_detail_collect_icon_2);
        } else {
            iv_collct.setImageResource(R.mipmap.item_set_detail_collect_icon_1);
        }
    }

    private Disposable reqSetDetail() {
        return APIRetrofit.getDefault().reqSetDetail(id)
                .compose(RxUtil.<BaseResult2<SetDetail>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<SetDetail>>() {
                    @Override
                    public void accept(BaseResult2<SetDetail> setResult2) throws Exception {
                        hideProgress();
                        if (setResult2.isSuccess()) {
                            setDetail = setResult2.getData();
                            if (null != setDetail) {
                                vp_tab.setAdapter(vpTabAdapter);
                                tab_2.setupWithViewPager(vp_tab);

                                tv_name.setText(setDetail.getName());
                                tv_price.setText("¥" + setDetail.getPrice());

                                GlideUtil.loadImg(Config.URL_IMG + setDetail.getPicture(), iv_img);
                            }
                        } else {
                            ToastUtils.showShort(setResult2.getMsg());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                    }
                });
    }

    private Disposable reqItemSetDetail() {
        return APIRetrofit.getDefault().reqItemSetDetail(id)
                .compose(RxUtil.<BaseResult2<ItemSetDetail>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<ItemSetDetail>>() {
                    @Override
                    public void accept(BaseResult2<ItemSetDetail> result2) throws Exception {
                        hideProgress();
                        if (result2.isSuccess()) {

                        } else {
                            ToastUtils.showShort(result2.getMsg());
                        }
                        detail = result2.getData();
                        if (null != detail) {
                            vp_tab.setAdapter(vpTabAdapter);
                            tab_2.setupWithViewPager(vp_tab);

                            tv_name.setText(detail.getName());
                            tv_price.setText("¥" + detail.getPrice());

                            GlideUtil.loadImg(Config.URL_IMG + detail.getPicture(), iv_img);
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                    }
                });
    }

    // 项目收藏
    private Disposable reqItemCollect(final String type) {
        return APIRetrofit.getDefault().reqProjectCollect(Global.HEADER, type, id)
                .compose(RxUtil.<BaseResult2<List>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<List>>() {
                    @Override
                    public void accept(BaseResult2<List> listBaseResult2) throws Exception {
                        hideProgress();
                        if (listBaseResult2.isSuccess()) {
                            if (!TextUtils.isEmpty(type)) {
                                isCollect = true;
                            } else {
                                reqItemCollect("1");
                            }
                        } else {
                            if (!TextUtils.isEmpty(type)) {
                                isCollect = false;
                            } else {
                                reqItemCollect("1");
                            }
                        }
                        setCollectIcon();
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                        if (!TextUtils.isEmpty(type)) {
                            isCollect = false;
                        }
                        setCollectIcon();
                    }
                });
    }

    // 套餐收藏
    private Disposable reqSetCollect(final String type) {
        return APIRetrofit.getDefault().reqSetCollect(Global.HEADER, type, id)
                .compose(RxUtil.<BaseResult2<List>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<List>>() {
                    @Override
                    public void accept(BaseResult2<List> listBaseResult2) throws Exception {
                        hideProgress();
                        if (listBaseResult2.isSuccess()) {
                            if (!TextUtils.isEmpty(type)) {
                                isCollect = true;
                            } else {
                                reqSetCollect("1");
                            }
                        } else {
                            if (!TextUtils.isEmpty(type)) {
                                isCollect = false;
                            } else {
                                reqSetCollect("1");
                            }
                        }
                        setCollectIcon();
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                        if (!TextUtils.isEmpty(type)) {
                            isCollect = false;
                        }
                        setCollectIcon();
                    }
                });
    }

    // 项目/套餐详情 tab adapter
    private class VpTabAdapter extends FragmentPagerAdapter {

        public VpTabAdapter(@NonNull FragmentManager fm) {
            super(fm);
        }

        @NonNull
        @Override
        public Fragment getItem(int position) {
            if (TextUtils.equals("1", type)) {// 项目
                if (position == 0) {
                    return ItemSetDetail1Fragment.newInstance(type, detail);
                } else if (position == 1) {
                    return ItemSetDetail2Fragment.newInstance(type, detail);
                } else if (position == 2) {
                    return ItemDetail3Fragment.newInstance(type, detail);
                } else {
                    return ItemSetDetail1Fragment.newInstance(type, detail);
                }
            } else {// 套餐
                if (position == 0) {
                    return SetDetail1Fragment.newInstance(type, setDetail);
                } else if (position == 1) {
                    return SetDetail2Fragment.newInstance(type, setDetail);
                } else if (position == 2) {
                    return SetDetail3Fragment.newInstance(type, setDetail);
                } else {
                    return SetDetail1Fragment.newInstance(type, setDetail);
                }
            }
        }

        @Override
        public int getCount() {
            return 3;
        }

        @Nullable
        @Override
        public CharSequence getPageTitle(int position) {
            return HOME_MODELS[position];
        }
    }
}